package monitor

import (
	"context"
	"encoding/json"
	"gitee.com/alex_li/event-lite"
	"gitee.com/alex_li/gpio/internal/etc"
	"gitee.com/alex_li/gpio/internal/pin"
	"github.com/lishimeng/go-log"
	"github.com/lishimeng/x/container"
)

type LedEvent struct {
	LedNumber int       `json:"ledNumber"`
	Operation pin.Value `json:"operation"` // 1:on / 0:off
}

func watchEvent(ctx context.Context) (err error) {

	handler := event_lite.New(ctx)
	container.Add(&handler)
	log.Info("open event server: %d", etc.Config.Event.Port)
	err = handler.StartServer(etc.Config.Event.Port)
	if err != nil {
		return
	}

	handler.Subscribe(etc.Config.Event.Topic, func(event event_lite.Event) {
		p := event.Payload
		log.Info("event topic %s", event.Channel)
		log.Info("event payload %s", event.Payload)
		var ledEvent LedEvent
		err = json.Unmarshal([]byte(p), &ledEvent)
		if err != nil {
			return
		}
		if etc.Config.Pins.Dev == 1 {
			log.Info("dev mode, skip others")
			return
		}
		var gpioManager pin.GPIOManager
		err = container.Get(&gpioManager)
		if err != nil {
			return
		}
		pinMap := gpioManager.GetPinMap()
		var ledState = ledEvent.Operation
		var otherState pin.Value = pin.LOW
		for number, gpioPin := range pinMap {
			if number == ledEvent.LedNumber {
				log.Info("change led state:%d[%d]", number, ledState)
				_ = gpioPin.Write(ledState)
			} else {
				_ = gpioPin.Write(otherState)
			}
		}
	})

	return
}
